let text = require('../../../../common/util/text.js')
let util = require('../../../../common/util/util.js') 
Page({
    data: {
        value: '',
        id: '',
        week: '',
        num: '',
        day: '',
        xState: false,
        color:'',
        icon:'',
        current:1,
        is_synchronize:true,
        is_anonymous:true,
        treatment_item_id:'',
        days:'',
        showtips:false,
        step:false,
        isEmotionalDiary:false, // 是否是情绪日记
        isEmotionalDiaryM:false, //是否显示弹窗
        EmotionalClass:[], //情绪分类列表
        EmotionalData:[], //
        currentType:1,
        currentindex:0,
        Emotional:{
          name:''
        } , //选择的情绪及程度
        index:'',// 情绪所在索引
        mode: '',
        dateVisible: false,
        datetime: '',
        datetimeText: '',
        currentDate:'',//当前选中日期值
        scrollTop:0
    },
    onShow:function(){
      getApp().globalData.lock=false
      this.setData({
        datetime: util.formatTime_e(new Date()),
        currentDate:util.formatTime_e(new Date())
      })
    },
    onLoad: function (opt) {
      console.log(opt)
      this.setData({
          week: Number(opt.week),
          num: opt.num,
          title: opt.title,
          id: opt.id,
          days:Number(opt.day),
          treatment_item_id:opt.treatment_item_id
      })
      this.xTepInit(opt.num)
      this.xGetEmotionalListType()
    },
    xChildReload: function () {
      var pages = getCurrentPages();//当前页面栈
      if (pages.length > 1) {
        var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
        beforePage.xInfo();//触发父页面中的方法
      }
    },
    onShareAppMessage: function () {
      return {
        title: this.data.day.writing_class_name
      };
    },
    afterleave:function(){
      this.setData({
        isEmotionalDiaryM:false
      })
    },
    EmotionalDiary:function(e){
      let that =this
      this.setData({
        showtips:true,
        isEmotionalDiaryM:true,
        index:e.currentTarget.dataset.index
      })
      // if(that.data.EmotionalClass.length==0){
      //   // that.xGetEmotionalList()
      //   that.xGetEmotionalListType()
      // }
    },
    // 获取情绪所有情绪
    // xGetEmotionalList:function(){
    //   let that =this
    //   wx.cloud.callFunction({
    //     name: 'data_dictionary',
    //     data: {
    //       action: "get_data_by_class",
    //       classification:"emotion"
    //     }
    //   }).then(res => {
    //     for(let index in res.result){
    //       res.result[index].check =false
    //     }
    //     that.setData({
    //       EmotionalList:res.result
    //     })
    //   })
    // },
    // 获取情绪分类
    xGetEmotionalListType:function(){
      let that =this
      wx.cloud.callFunction({
        name: 'data_dictionary',
        data: {
          action: "get_data_emotion_by_class",
          classification:"emotion",
        }
      }).then(res => {
        for(let index in res.result.emotion_data){
          res.result.emotion_data[index].check =false
        }
        for(let index in res.result.emotion_class){
          res.result.emotion_class[index].check = 0
        }
        that.setData({
          EmotionalClass:res.result.emotion_class,
          EmotionalData:res.result.emotion_data,
        })
      })
    },
    // 切换分类
    changeType:function(e){
      let that =this
      let v =e.currentTarget.dataset.v
      let index = e.currentTarget.dataset.index
      // wx.cloud.callFunction({
      //   name: 'data_dictionary',
      //   data: {
      //     action: "get_data_emotion_by_class",
      //     classification:"emotion",
      //     emotion_class_v:v //分类值
      //   }
      // }).then(res => {
      //   for(let index in res.result.emotion_data){
      //     res.result.emotion_data[index].check =false
      //   }
        that.setData({
      //     EmotionalData:res.result.emotion_data,
          currentType:v,
          currentindex:index,
          scrollTop:0
        })
      // })
    },
    // 选择情绪分类
    choose:function(e){
      let that =this
      let param = e.currentTarget.dataset.name
      let index  = e.currentTarget.dataset.index
      let currentindex = that.data.currentindex
      let check = e.currentTarget.dataset.check
      let num =0
      for(let index in that.data.EmotionalData){
        if(that.data.EmotionalData[index].check){
          num ++ 
        }
      }
      if(num ==2 && !check){
        wx.showToast({
          title: '最多选择两种情绪',
          icon:'none'
        })
      }else{
        that.setData({
          [`EmotionalData[${index}].check`]: !that.data.EmotionalData[index].check,
        })
        if(that.data.EmotionalData[index].check == true){
          that.setData({
            [`EmotionalClass[${currentindex}].check`]: that.data.EmotionalClass[currentindex].check +1,
          })
        }else{
          that.setData({
            [`EmotionalClass[${currentindex}].check`]: that.data.EmotionalClass[currentindex].check -1,
          })
        }
      }
    },
    chooseV:function(e){
      let param = e.currentTarget.dataset.level
      this.setData({
        ['Emotional.level']:param
      })
    },
    xTosetM:function(){
      wx.setStorageSync(this.data.treatment_item_id, this.data.treatment_item_id)
      this.setData({
          showtips:!this.data.showtips
      })
    },
    xToSetV:function(){
      let that = this
      for(let index in that.data.EmotionalData){
        if(that.data.EmotionalData[index].check ==true &&  that.data.Emotional.name.indexOf(that.data.EmotionalData[index].name) == -1){
          if(that.data.Emotional.name==''){
            that.setData({
              [`Emotional.name`]:that.data.EmotionalData[index].name
            })
          }else{
            that.setData({
              [`Emotional.name`]:that.data.Emotional.name+','+ that.data.EmotionalData[index].name
            })
          }
        }else if( !that.data.EmotionalData[index].check && that.data.Emotional.name.indexOf(that.data.EmotionalData[index].name,0) !==-1 ){
          let i = that.data.Emotional.name.indexOf(that.data.EmotionalData[index].name)
          if(i==0){
            that.setData({
              [`Emotional.name`]:that.data.Emotional.name.replace(that.data.EmotionalData[index].name, '')
            })
          }else{
            that.setData({
              [`Emotional.name`]:that.data.Emotional.name.replace( ','+ that.data.EmotionalData[index].name, '')
            })
          }
        }
      }
      if(that.data.Emotional.name.substr(0,1) == ","){
        that.setData({
          [`Emotional.name`]:that.data.Emotional.name.replace( ',', '')
        })
      }
      if(that.data.Emotional.name && that.data.Emotional.level){
        let form = that.data.day.writing_template
        let index = that.data.index
        form[index].content = that.data.Emotional.name+ ','+ '程度:'+that.data.Emotional.level
        this.setData({
          showtips:false,
          [`day.writing_template`] : form
        })
      }else if(that.data.Emotional.name==''){
        wx.showToast({
          title: '请选择情绪',
          icon:'none'
        })
      }else if(!that.data.Emotional.level){
        wx.showToast({
          title: '请选择程度',
          icon:'none'
        })
      }
    },
    xSetStep:function(){
      this.setData({
        step:true
      })
      wx.pageScrollTo({
        duration: 0,
        scrollTop:0
      })
    },
    sliderchange:function(e){
      let that = this
      let data = e.detail.value
      let form = that.data.day.writing_template
      let params = e.currentTarget.dataset
      form[params.index].content = data
      this.setData({
          [`day.writing_template`] : form
      })
    },
    // 选择日期  
    showPicker(e) {
      const { mode } = e?.currentTarget?.dataset;
      this.setData({
        mode,
        [`${mode}Visible`]: true,
      });
    },
    hidePicker() {
      const { mode } = this.data;
      this.setData({
        [`${mode}Visible`]: false,
      });
    },
    onConfirm(e) {
      const { value } = e?.detail;
      const { mode } = this.data;
      this.setData({
        [mode]: value,
        [`${mode}Text`]: value,
        currentDate:value
      });
  
      this.hidePicker();
    },  
    onColumnChange(e) {
    },
    // 获取日记信息
    xTepInit: function (id) {
        let that = this
        let _dataObj ={
            parameter_id: id
        }
        wx.cloud.callFunction({
            name: 'digital_therapy',
            data: {
                action: "get_write_task_info",
                dataObj: _dataObj
            }
        }).then(res => {
            let data = res.result
            data.writing_class_desc=text.text(data.writing_class_desc)
            for(let index in data.writing_template){
              if(data.writing_template[index].display_type ==2 ){
                that.setData({
                  isEmotionalDiary:true
                })
              }
            }
            that.setData({
                day : data
            })
        })
    },
    input: function (e) {
        let that = this
        let data = e.detail.value
        let form = that.data.day.writing_template
        let params = e.currentTarget.dataset
        form[params.index].content = data
        this.setData({
            [`day.writing_template`] : form
        })
    },
    xToset: function(e){
      let state= e.currentTarget.dataset.state;
      
      this.setData({
        is_synchronize:state,
        current:state==true ? 1 : 2
      })
    },
    xTosetanonymous: function(e){
      // let state= e.currentTarget.dataset.state;
      this.setData({
        is_anonymous: !this.data.is_anonymous
      })
      console.log(this.data.is_anonymous)
    },
    xSub: function () {
        let that = this
        let form = that.data.day.writing_template
        if(getApp().globalData.lock==true){
          return
        }
        let key =0
        for(var i in form){
            if(form[i].content == '' || form[i].content == undefined){
              key=key+1
            }
        }
        if(key>0){
          wx.showModal({
            title: "提示",
            content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
            showCancel: false,
            confirmText:'好的'
          })
          return
        }
        if(!that.data.currentDate){
          wx.showModal({
            title: "提示",
            content: "请选择事件发生时间",
            showCancel: false,
            confirmText:'好的',
            success:function(res){
              if (res.confirm) {
                wx.pageScrollTo({
                  scrollTop: 0,
                })
              }
            }
          })
          return
        }

        // wx.reportEvent("test_event_name", {
        //   "test_key1": "",
        //   "test_key2": 0
        // })
        getApp().globalData.lock=true
        if(that.data.day.is_subscribe){
          wx.requestSubscribeMessage({
            tmplIds: [
                "s-Mq0IcYoqL6yFi0ttPSTngYneBzFi6O7NKAVRWT0pM",
                "TBmwFgapJW30qV3VfL517MUqLvbyftvQhNWD6rWideI"
            ],
            success: (res) => {
                if (res['s-Mq0IcYoqL6yFi0ttPSTngYneBzFi6O7NKAVRWT0pM'] === 'accept') {
                    wx.cloud.callFunction({
                        name: 'message_subscribe',
                        data: {
                            action: "add_subscribe",
                            dataObj: {
                                templateid: "s-Mq0IcYoqL6yFi0ttPSTngYneBzFi6O7NKAVRWT0pM",
                                subscribe_status_string: "accept"
                            }
                        }
                    }).then(res => {
                        wx.showToast({
                            title: '订阅成功',
                            icon: 'none',
                            duration: 1000,
                        })
                    })
                }
            },
            fail() { },
            complete () {
              that.xSave()
            }
        })
        }else{
          that.xSave()
        }
        
    },
    xSave:function(){
      let that = this
      let week = parseInt(that.data.week)
      let value = that.data.value
      let title = that.data.title
      let num = that.data.num
      let treatment_item_id =that.data.treatment_item_id
      let day =that.data.days
      let form = that.data.day.writing_template
      wx.showLoading({
        title: '保存中',
      })
      let _dataObj ={
          week: week ,
          job_type: 2 ,
          day:day,
          treatment_item_id:treatment_item_id,
          time_occurrence:that.data.currentDate,
          writing_practice_return: {
              writing_class_number: num,
              json_content : form
          },
          is_synchronize:false,//是否同步至小组贴
          is_anonymous:that.data.is_anonymous //是否匿名发布
      }
      wx.cloud.callFunction({
          name: 'digital_therapy',
          data: {
              action: "add_job_record",
              dataObj: _dataObj
          }
      }).then(res => {
          wx.hideLoading()
          wx.showToast({
              title: '保存成功',
              icon: 'none',
              success: () => {
                  setTimeout( () => {
                    getApp().globalData.lock=false
                    wx.navigateBack({
                      delta: 1,
                    })
                    that.xChildReload()
                  } , 2000)
              }
          })
      }).catch(err=>{
        wx.hideLoading()
        getApp().globalData.lock=false
      })
    },
    xInfoShwo: function () {
        let that = this
        that.setData({
            xState : true
        })
    },
    xToclose :function ( ){
        let that = this
        that.setData({
            xState : false
        })
    }
})